package com.codefish.framework.spring.context.support;

import com.codefish.framework.spring.beans.exception.BeansException;
import com.codefish.framework.spring.beans.factory.config.IBeanPostProcessor;
import com.codefish.framework.spring.beans.factory.support.BeanDefinition;
import com.codefish.framework.spring.context.event.IApplicationListener;

/**
 * 处理注册为监听者的bean
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/10/10 下午 05:14
 */
public class ApplicationListenerDetector implements IBeanPostProcessor {
    private final AbstractApplicationContext applicationContext;

    public ApplicationListenerDetector(AbstractApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        BeanDefinition beanDefinition = applicationContext.getBeanFactory().getBeanDefinition(beanName);
        //只注册单例的监听者
        if (beanDefinition != null && beanDefinition.isSingleton()) {
            if (bean instanceof IApplicationListener) {
                applicationContext.addApplicationListener((IApplicationListener<?>) bean);
            }
        }
        return bean;
    }

}
